package com.jie.scanbarcode

import android.graphics.Rect
import com.blankj.utilcode.util.LogUtils
import com.google.mlkit.vision.barcode.BarcodeScannerOptions
import com.google.mlkit.vision.barcode.BarcodeScanning
import com.google.mlkit.vision.barcode.common.Barcode
import com.google.mlkit.vision.common.InputImage

object BarCodeHelper {

    //配置当前扫码格式
    private val options = BarcodeScannerOptions.Builder()
            .setBarcodeFormats(
                    Barcode.FORMAT_ALL_FORMATS,
//                    Barcode.FORMAT_QR_CODE,
//                    Barcode.FORMAT_AZTEC
            )
            .build()

    // 扫描图片
    fun process(inputImage: InputImage, successListener: (Barcode, Int, Int) -> Unit,
                failureListener: (Exception) -> Unit, completeListener: (() -> Unit)? = null,
                analysisRect : Rect? = null){
        // 初始化扫描对象
        val mBarcodeClient = BarcodeScanning.getClient(options)
        mBarcodeClient.process(inputImage)
                .addOnSuccessListener {
                    if (it.isNotEmpty()) {
                        // 获取第一个在扫描区域内的结果
                        var result : Barcode? = null
                        it.forEachIndexed { index, barcode ->
                            // 若结果二维码在扫描区域内，则返回该结果
                            val isContainsAnalysis = analysisRect == null || analysisRect.contains(barcode.boundingBox?:Rect())
                            LogUtils.i("barcode result : $index [${barcode.rawValue}] " +
                                    "resultBox:(${barcode.boundingBox}) analysisBox:(${analysisRect}) " +
                                    "isContainsAnalysis：$isContainsAnalysis")
                            if (isContainsAnalysis && result == null) {
                                // 只取第一个在扫描区域内的结果
                                result = barcode
                            }
                        }
                        result?.run {
                            successListener.invoke(this, inputImage.width, inputImage.height)
                        }
                    }
                }
                .addOnFailureListener{
                    failureListener.invoke(it)
                }
                .addOnCompleteListener {
                    // 完成之后就停解析
                    mBarcodeClient.close()
                    completeListener?.invoke()
                }
    }

}